package com.app.messenger;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

public class RemoteService extends Service {

    private RemoteHandler mHandler;
    private Messenger mMessenger;
    private static int mCount = 1;


    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new RemoteHandler();
        mMessenger = new Messenger(mHandler);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }


    static class RemoteHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Messenger clientMessenger = msg.replyTo;
                if (clientMessenger != null) {
                    try {
                        clientMessenger.send(Message.obtain(null, 1, mCount++, 0));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
